<script setup lang="js">
    import { ElMessage, ElLoading } from "element-plus";
    import { ref, defineExpose, defineProps, watch } from 'vue'
    import request from '../../request/axios'

    const props = defineProps({
        sessionId: {
            type: String,
            required: ''
        },
    });

    // 选择知识库
    const knowledgeId = ref('')
    const checkedVisible = ref(false)
    const knowledgeList = ref([])
    const knowledgeDataMed = ref([])
    const knowledgeActionList = ref([])
    const dataMedActionList = ref([])
    const getKnowledgeList = async () => {
        try {
            // 获取DataMed内置数据库
            const res1 = await request.getV2({ url: '/v1/api-db-list' })
            knowledgeDataMed.value = res1.data
        } catch (error) {
            console.log(error)
        }
        try {
            const data = {}
            data.page = 1
            data.pageNum = 10
            const res = await request.getV2({ url: '/v1/api-knowledge-list', data })
            knowledgeList.value = res.data.list
            getKnowledgeActionList()
        } catch (error) {
            console.log(error)
        }
    }

    const addKnowledge = (item, index, type) => {
        if (type == 0) {
            knowledgeActionList.value.push(item)
            knowledgeList.value.splice(index, 1);
        } else if (type == 1) {
            knowledgeList.value.push(item)
            knowledgeActionList.value.splice(index, 1);
        } else if (type == 2) {
            dataMedActionList.value.push(item)
            knowledgeDataMed.value.splice(index, 1);
        } else if (type == 3) {
            knowledgeDataMed.value.push(item)
            dataMedActionList.value.splice(index, 1);
        }
    }
    const setCheckedVisible = () => {
        getKnowledgeList()
        const loading = ElLoading.service({
            lock: true,
            text: 'Loading',
            background: 'rgba(255, 255, 255, 0.7)',
        })
        setTimeout(() => {
            loading.close()
            checkedVisible.value = !checkedVisible.value
        }, 400);
    }
    const clickCheckedBack = async () => {
        const data = {};
        data.session_id = props.sessionId;
        data.knowledge_id = knowledgeActionList.value.map(item => item.id).join(','); // 知识库id
        data.database_name = dataMedActionList.value.map(item => item.name).join(','); // 内置知识库名称
        // if (knowledgeActionList.value.length + dataMedActionList.value.length == 0) return ElMessage.warning("请选择知识库！")
        const res = await request.postV2({ url: '/v1/api-binding-knowledge', data })
        localStorage.setItem("knowledgeId", data.knowledge_id)
        localStorage.setItem("databaseName", data.database_name)
        localStorage.setItem("sessionId", res.data.session_id)
        checkedVisible.value = false
        if (res.code == 200) return ElMessage.success("操作成功!")
    }

    // 回显选中的系统知识库
    const getDataMedActionList = async () => {
        dataMedActionList.value = [];
        if (!localStorage.getItem("databaseName") || localStorage.getItem("databaseName") == undefined) return;
        const knowledgeMap = localStorage.getItem("databaseName").split(',')
        knowledgeDataMed.value.forEach((element, index) => {
            if (knowledgeMap.some(val => val == element.name)) {
                addKnowledge(element, index, 2);
            }
        });
    }

    // 回显选中的自定义知识库
    const getKnowledgeActionList = async () => {
        knowledgeActionList.value = [];
        getDataMedActionList()
        if (!localStorage.getItem("knowledgeId") || localStorage.getItem("knowledgeId") == undefined) return;
        const knowledgeMap = localStorage.getItem("knowledgeId").split(',')
        knowledgeList.value.forEach((element, index) => {
            if (knowledgeMap.some(val => val == element.id)) {
                addKnowledge(element, index, 0);
            }
        });
    }

    watch(
        () => localStorage.getItem("databaseName") || localStorage.getItem("knowledgeId"),
        () => {
            getKnowledgeActionList()
        }
    )

    const setTitleShow = () => {
        return knowledgeActionList.value.length + knowledgeList.value?.length || 0 + dataMedActionList.value.length > 0 ? true : false
    }
    const setEmptyShow = () => {
        return knowledgeActionList.value.length + knowledgeList.value?.length || 0 + dataMedActionList.value.length === 0 ? false : true
    }

    setTimeout(() => {
        console.log(setTitleShow());

    }, 1000)

    // 暴露方法给父组件
    defineExpose({
        setCheckedVisible
    });
</script>

<template>
    <div class="build-content" v-loading="buildLoading">
        <el-dialog v-model="checkedVisible" title="绑定知识库">
            <div class="checked-content">
                <div class="checked-title" v-if="setTitleShow()">已选知识库列表</div>
                <div class="checked-box action" v-for="(item,index) in knowledgeActionList" :key="index">
                    <img src="../../assets//image//icon/collection-icon.png" />
                    <div class="checked-name">{{item.knowledge_base_name}}</div>
                    <Delete width="16px" color="red" style="cursor: pointer;" @click="addKnowledge(item,index,1)" />
                </div>
                <!-- <div class="checked-box action" v-for="(item,index) in dataMedActionList" :key="index">
                    <img src="../../assets//image//icon/collection-icons.png" />
                    <div class="checked-name">{{item.name}}</div>
                    <Delete width="16px" color="red" style="cursor: pointer;" @click="addKnowledge(item,index,3)" />
                </div> -->

                <!-- <div class="checked-title" v-if="setTitleShow()">
                    DataMed内置数据库</div>
                <div class="checked-box" style="cursor: pointer;" v-for="(item,index) in knowledgeDataMed" :key="item"
                    @click="addKnowledge(item,index,2)">
                    <img src="../../assets//image//icon/collection-icons.png" />
                    <div class="checked-name">{{item.name}}</div>
                </div> -->

                <div class="checked-title" v-if="setTitleShow()">
                    未选知识库列表
                </div>
                <div class="checked-box" style="cursor: pointer;" v-for="(item,index) in knowledgeList" :key="item"
                    @click="addKnowledge(item,index,0)">
                    <div class="checked-item" v-if="item.selected == 1">
                        <img src="../../assets//image//icon/collection-icon.png" />
                        <div class="checked-name">{{item.knowledge_base_name}}</div>
                    </div>

                </div>
                <el-empty :image-size="160" style="margin: 0 auto;" description="暂无数据"
                    v-if="!setEmptyShow() && knowledgeList.length == 0" />
                <div style="width: 100%;display: flex;justify-content: end;">
                    <el-button type="primary" @click="clickCheckedBack">完成</el-button>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<style scoped lang="scss">
    .checked-content {
        display: flex;
        flex-wrap: wrap;
        align-items: center;

        .checked-title {
            color: #000;
            width: 100%;
            font-weight: bold;
            padding-left: 10px;
            margin: 20px 0;
        }

        .checked-box {
            width: calc(22% - 10px);
            padding: 6px 10px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            border-radius: 9px;
            margin: 0 7px 10px;
            box-shadow: 0px 0px 7px 0px rgba(0, 0, 0, 0.08);

            .checked-item {
                display: flex;
                align-items: center;
                justify-content: space-between;
                width: 100%;
                height: 100%;
            }

            img {
                width: 30px;
            }

            .checked-name {
                flex: 1;
                margin-left: 4px;
            }

            &.action {
                background-color: #C5D7FF;
            }
        }
    }
</style>